package hust.iamk.backup;

import java.net.URL;
import java.util.ArrayList;
import java.util.Date;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.TabActivity;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.TypedArray;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.OpenableColumns;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TabHost;
import android.widget.Toast;

import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.GeneratePresignedUrlRequest;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.ResponseHeaderOverrides;
import com.hust.iamk.R;

public class BackupCloud extends TabActivity {
	private final static int PHOTO_SELECTED = 1;
	private AmazonS3Client s3Client = new AmazonS3Client(
			new BasicAWSCredentials(Constants.ACCESS_KEY_ID,
					Constants.SECRET_KEY));
	private GridView gridView;
	private GridViewAdapter customGridAdapter;

	@SuppressWarnings("deprecation")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_backup_cloud);
		TabHost.TabSpec spec = getTabHost().newTabSpec("tagDevice");

		spec.setContent(R.id.upload);
		spec.setIndicator("Device");
		getTabHost().addTab(spec);

		spec = getTabHost().newTabSpec("tagCloud");
		spec.setContent(R.id.gridView);
		spec.setIndicator("Cloud");
		getTabHost().addTab(spec);

		getTabHost().setCurrentTab(0);

		new S3GeneratePresignedUrlTask().execute();
		
		Button btnSelect = (Button) findViewById(R.id.btnSelect);
		btnSelect.setOnClickListener(onSelect);

		s3Client.setRegion(Region.getRegion(Regions.US_WEST_2));

		gridView = (GridView) findViewById(R.id.gridView);
		customGridAdapter = new GridViewAdapter(this, R.layout.row_grid,
				getData());
		gridView.setAdapter(customGridAdapter);
		gridView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long id) {
				// TODO Auto-generated method stub
				Toast.makeText(getApplicationContext(), position + " Selected",
						Toast.LENGTH_SHORT).show();
				Log.d("Debug", "Click");
			}
		});

	}

	private View.OnClickListener onSelect = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			Intent intent = new Intent();
			intent.setType("image/*");
			intent.setAction(Intent.ACTION_GET_CONTENT);
			startActivityForResult(
					Intent.createChooser(intent, "Select Picture"),
					PHOTO_SELECTED);
		}
	};

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case PHOTO_SELECTED:
			if (resultCode == RESULT_OK) {
				Uri selectedImage = data.getData();
				new S3PutObjectTask().execute(selectedImage);
			}
		default:
			break;
		}
	};

	private ArrayList getData() {
		final ArrayList imageItems = new ArrayList();
		// retrieve String drawable array
		TypedArray imgs = getResources().obtainTypedArray(R.array.image);
		for (int i = 0; i < imgs.length(); i++) {
			Bitmap bitmap = BitmapFactory.decodeResource(this.getResources(),
					imgs.getResourceId(i, -1));
			imageItems.add(new ImageItem(bitmap, "Image#" + i));
		}

		return imageItems;
	}

	// Display an Alert message for an error or failure.
	protected void displayAlert(String title, String message) {

		AlertDialog.Builder confirm = new AlertDialog.Builder(this);
		confirm.setTitle(title);
		confirm.setMessage(message);

		confirm.setNegativeButton(BackupCloud.this.getString(R.string.ok),
				new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {

						dialog.dismiss();
					}
				});

		confirm.show().show();
	}

	protected void displayErrorAlert(String title, String message) {

		AlertDialog.Builder confirm = new AlertDialog.Builder(this);
		confirm.setTitle(title);
		confirm.setMessage(message);

		confirm.setNegativeButton(BackupCloud.this.getString(R.string.ok),
				new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {

						BackupCloud.this.finish();
					}
				});

		confirm.show().show();
	}

	private class S3PutObjectTask extends AsyncTask<Uri, Void, S3TaskResult> {
		ProgressDialog dialog;

		protected void onPreExecute() {
			dialog = new ProgressDialog(BackupCloud.this);
			dialog.setMessage(BackupCloud.this.getString(R.string.uploading));
			dialog.setCancelable(false);
			dialog.show();
		}

		@Override
		protected S3TaskResult doInBackground(Uri... uris) {
			// TODO Auto-generated method stub
			if (uris == null || uris.length != 1) {
				return null;
			}
			Uri selectedImage = uris[0];
			ContentResolver resolver = getContentResolver();
			String fileSizeColumn[] = { OpenableColumns.SIZE };

			Cursor cursor = resolver.query(selectedImage, fileSizeColumn, null,
					null, null);
			cursor.moveToFirst();

			int sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE);

			String size = null;
			if (!cursor.isNull(sizeIndex)) {
				size = cursor.getString(sizeIndex);
			}
			cursor.close();

			ObjectMetadata metadata = new ObjectMetadata();
			metadata.setContentType(resolver.getType(selectedImage));
			if (size != null) {
				metadata.setContentLength(Long.parseLong(size));

			}

			S3TaskResult result = new S3TaskResult();
			try {
				PutObjectRequest por = new PutObjectRequest(
						Constants.getPictureBucket(),
						Constants.getAccount(BackupCloud.this) + "/"
								+ System.currentTimeMillis(),
						resolver.openInputStream(selectedImage), metadata);
				s3Client.putObject(por);
			} catch (Exception exception) {
				result.setErrorMessage(exception.getMessage());
			}

			return result;
		}

		protected void onPostExecute(S3TaskResult result) {
			dialog.dismiss();
			if (result.getErrorMessage() != null) {
				displayErrorAlert(
						BackupCloud.this
								.getString(R.string.upload_failure_title),
						result.getErrorMessage());
			} else {
				// Action success
			}
		}
	}

	private class S3TaskResult {
		String errorMessage = null;
		Uri uri = null;

		public String getErrorMessage() {
			return errorMessage;
		}

		public void setErrorMessage(String errorMessage) {
			this.errorMessage = errorMessage;
		}

		public Uri getUri() {
			return uri;
		}

		public void setUri(Uri uri) {
			this.uri = uri;
		}
	}

	private class S3GeneratePresignedUrlTask extends
			AsyncTask<Void, Void, S3TaskResult> {

		protected S3TaskResult doInBackground(Void... voids) {

			S3TaskResult result = new S3TaskResult();

			try {
				// Ensure that the image will be treated as such.
				ResponseHeaderOverrides override = new ResponseHeaderOverrides();
//				override.setContentType("image/png");

				// Generate the presigned URL.

				// Added an hour's worth of milliseconds to the current time.
				Date expirationDate = new Date(
						System.currentTimeMillis() + 3600000);
				GeneratePresignedUrlRequest urlRequest = new GeneratePresignedUrlRequest(
						Constants.getPictureBucket(), Constants.PICTURE_NAME);
//				urlRequest.setExpiration(expirationDate);
//				urlRequest.setResponseHeaders(override);

				URL url = s3Client.generatePresignedUrl(urlRequest);

				result.setUri(Uri.parse(url.toURI().toString()));

			} catch (Exception exception) {

				result.setErrorMessage(exception.getMessage());
			}

			return result;
		}

		protected void onPostExecute(S3TaskResult result) {

			if (result.getErrorMessage() != null) {

			} else if (result.getUri() != null) {

				// Display in Browser.
				Log.i("URL", result.getUri().toString());
				startActivity(new Intent(Intent.ACTION_VIEW, result.getUri()));
				
			}
		}
	}
}
